#pragma once
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <functional>
#include <pthread.h>
#include <cstring>
#include <cstdio>
#include <string>
#include"Log.hpp"
using namespace LogMoudle;
namespace ThreadMoudle
{
    static uint32_t number = 1; // bug
    class thread
    {
        using func_t = std::function<void()>;

    private:
        void EnableDetach()
        {
            _isdetach = true;
        }
        void EnableRunning()
        {
            _isrunning = true;
        }
        static void *Routine(void *args)
        {
            thread *self = (thread *)args;
            self->EnableRunning();
            if (self->_isdetach)
            {
                self->Detach();
            }
            pthread_setname_np(self->_id, self->_name.c_str());
            self->_func();
            return nullptr;
        }

    public:
        thread(func_t func)
            : _id(0), _isrunning(false), _isdetach(false), _func(func), _res(nullptr)
        {
            _name = "thread-" + std::to_string(number++);
        }
        bool Start() // 创建线程
        {
            if (_isrunning)
            {
                return false;
            }
            int n = pthread_create(&_id, nullptr, Routine, this);
            if (n != 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        void Detach() // 开启线程分离模式
        {
            if (_isdetach)
            {
                return;
            }
            if (_isrunning)
            {
                pthread_detach(_id);
            }
            EnableDetach();
        }
        bool Stop() // 终止线程
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_id);
                if (n != 0)
                {
                    return false;
                }
                else
                {
                    _isrunning = false;
                    return true;
                }
            }
            return false;
        }
        void Join() // 等待线程
        {
            if (_isdetach) // 分离模式下的线程不需要被等待
            {
                return;
            }
            int n = pthread_join(_id, &_res);
            if (n != 0)
            {
                LOG(loglevel::DEBUG) << "Join线程失败";
            }
            else
            {
                LOG(loglevel::DEBUG) << "Join线程成功";
            }
        }
        std::string Name()
        {
            return _name;
        }
        ~thread()
        {
        }

    private:
        pthread_t _id;
        void *_res;
        std::string _name;
        bool _isrunning;
        bool _isdetach;
        func_t _func;
    };
}
